package top.banner.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import top.banner.entity.JDContent;
import top.banner.utils.HTMLParseUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author XGL
 */
@Service
public class JDContentService {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @SneakyThrows
    public Boolean parseJDContent(String keyword) {
        final List<JDContent> list = new HTMLParseUtils().parseJD(keyword);
        final BulkRequest request = new BulkRequest();
        request.timeout("2m");
        for (JDContent it : list) {
            request.add(new IndexRequest("jd_goods")
                    .source(objectMapper.writeValueAsString(it), XContentType.JSON));
        }
        final BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    @SneakyThrows
    public List<Map<String, Object>> searchPage(String keyword, int page, int size) {

        final SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(page);
        sourceBuilder.size(size);

        //高亮
        sourceBuilder.highlighter(new HighlightBuilder().field("title").preTags("<span style='color:red'>").postTags("</span>"));

        //精准搜索
        final TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);
        final SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            final Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            final HighlightField title = highlightFields.get("title");
            final Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //解析高亮字段
            if (title != null) {
                final Text[] fragments = title.fragments();
                StringBuilder n_title = new StringBuilder();
                for (Text fragment : fragments) {
                    n_title.append(fragment);
                }
                sourceAsMap.put("title", n_title.toString());
            }
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

}
